﻿function(){     
    doc = this;    for (var idx = 0; idx < doc.companies.length; idx++) 
    {
        var currentVal = doc.companies[idx].CompanyScore;
        var k = idx - 1;       
        
        while(k >= 0)
        {           
            if (doc.companies[k].CompanyScore == currentVal)
                k--;
            else
                break;           
        }        

        if (k < 0)
            k = 0;
        doc.companies[idx].Rank = k + 1;
        if (doc.GroupCount > 1)
        {
            doc.companies[idx].RankPercent = (k+1)/(doc.GroupCount-1);
        }
    }
      var key    = doc._id;    
    var values  = doc;     
    emit(key, values);  
} 